// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;
// 摇杆 组件类
@ccclass
export default class RockingBar extends cc.Component {

    @property(cc.Node)
    rocker:cc.Node = null;
    Max_r :number =50;
    dir: cc.Vec2 = null;
    start () {
        this.rocker.x = 0;
        this.rocker.y = 0;
        this.dir = cc.v2(0,0);

        this.rocker.on(cc.Node.EventType.TOUCH_START,function(e){
            let w_pos = e.getLocation();
            let pos = this.node.convertToNodeSpaceAR(w_pos);
            let len = pos.mag();//获取向量长度
            this.dir.x = pos.x / len;
            this.dir.y = pos.y / len;
            if(len > this.Max_r){
                pos.x = this.Max_r * pos.x / len;
                pos.y = this.Max_r * pos.y / len;
            }
            this.rocker.setPosition(pos);
        },this);

        this.rocker.on(cc.Node.EventType.TOUCH_MOVE,function(e){
            let w_pos = e.getLocation();
            let pos = this.node.convertToNodeSpaceAR(w_pos);
            let len = pos.mag();
            this.dir.x = pos.x / len;
            this.dir.y = pos.y / len;
            if(len > this.Max_r){
                pos.x = this.Max_r * pos.x / len;
                pos.y = this.Max_r * pos.y / len;
            }
            this.rocker.setPosition(pos);
        },this);

        this.rocker.on(cc.Node.EventType.TOUCH_END,function(e){
            this.rocker.setPosition(cc.v2(0,0));
            this.dir = cc.v2(0, 0);
        },this);

        this.rocker.on(cc.Node.EventType.TOUCH_CANCEL,function(e){
            this.rocker.setPosition(cc.v2(0,0));
            this.dir = cc.v2(0, 0);
        },this);
    }

    // update (dt) {}
}
